/*
 * Copyright 2016 requery.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.requery.ohos.example.app.slice;

import io.requery.ohos.example.app.PeopleApplication;
import io.requery.ohos.example.app.ResourceTable;
import io.requery.ohos.example.app.utils.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.requery.Persistable;
import io.requery.ohos.example.app.model.Address;
import io.requery.ohos.example.app.model.AddressEntity;
import io.requery.ohos.example.app.model.Person;
import io.requery.ohos.example.app.model.PersonEntity;
import io.requery.ohos.example.app.model.Phone;
import io.requery.ohos.example.app.model.PhoneEntity;
import io.requery.reactivex.ReactiveEntityStore;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.TextField;

/**
 * Simple activity allowing you to edit a Person entity using data binding.
 */

public class PersonEditActivity extends AbilitySlice {
    static final String EXTRA_PERSON_ID = "personId";
    private static final String TAG = PersonEditActivity.class.getName();

    private ReactiveEntityStore<Persistable> data;
    private Person person;
    private Button save;
    private Image img;
    private TextField name;
    private TextField email;
    private TextField street;
    private TextField city;
    private TextField state;
    private TextField zip;
    private TextField country;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_edit_person);
        initLayout();
        data = ((PeopleApplication) getAbility()).getData();
        int personId = intent.getIntParam(EXTRA_PERSON_ID, -1);

        if (personId == -1) {
            person = new PersonEntity();
            setPerson(person);
        } else {
        data.findByKey(PersonEntity.class, personId)
                .subscribe(person -> setPerson(person));
        }

        save.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                savePerson();
            }
        });
    }

    private void initLayout() {
        name = (TextField) findComponentById(ResourceTable.Id_name);
        email = (TextField) findComponentById(ResourceTable.Id_email);
        city = (TextField) findComponentById(ResourceTable.Id_city);
        street = (TextField) findComponentById(ResourceTable.Id_street);
        state = (TextField) findComponentById(ResourceTable.Id_state);
        zip = (TextField) findComponentById(ResourceTable.Id_zip);
        country = (TextField) findComponentById(ResourceTable.Id_country);
        save = (Button) findComponentById(ResourceTable.Id_button_save);
    }

    private void setPerson(Person per) {
        this.person = per;
        name.setText(per.getName());
        email.setText(per.getEmail());

        if (per.getAddress() != null) {
            Address var10002 = per.getAddress();
            if (var10002 != null) {
                this.street.setText(var10002.getLine1());
                this.city.setText(var10002.getCity());
                this.zip.setText(var10002.getZip());
                this.state.setText(var10002.getState());
                this.country.setText(var10002.getCountry());
            }
        }
    }

    private void savePerson() {
        person.setName(name.getText());
        person.setEmail(email.getText());

        Address address = person.getAddress();
        if (address == null) {
            address = new AddressEntity();
            person.setAddress(address);
        }
        address.setLine1(street.getText());
        address.setCity(city.getText());
        address.setZip(zip.getText());
        address.setState(state.getText());
        address.setCountry(country.getText());
        // save the person

        Single<Person> single = person.getId() == 0 ? data.insert(person) : data.update(person);
        single.subscribeOn(Schedulers.single())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object obj) throws Exception {
                        this.accept((Person) obj);
                    }

                        /**
                         * accept
                         * @param person Person data to be saved
                         */
                        public void accept(Person person) {
                            PersonEditActivity.this.terminate();
                        }
                    });
    }
}
